from multiprocessing import Pool
from pymongo import MongoClient
# from snownlp import SnowNLP
from time import sleep
from PIL import Image
import string
import signal
import time
import sys
import cv2
import re
import os

def signal_handler(signal, frame) :
    os.system("adb shell rm /sdcard/screenshot.png >nul 2>&1")
    sys.exit(0)


def get_target(f) :

    img = cv2.imread(f, 0)
    h = img.shape[0]
    repl = '!"#$%&\'()*+,-/:;<=>?@[\\]^_`{|}~“”、，。 《》°「‖'
    # 标点符号的代替为.

    os.system("tesseract %s %s --dpi 300 -l chi_sim makebox >nul 2>&1" %(f, f))
    boxcontext = open(f+'.box', mode='r', encoding='UTF8').read()

    context = ''.join(re.split(r' .+\n', boxcontext)).translate(str.maketrans('','', repl))

    # if MongoClient()['db']['5-19'].find({'Q':{'$regex': '^%s' %context[:5] }}).count() == 1:

    char = MongoClient()['db']['5-19'].find_one({'Q':{'$regex': '^%s' %context[:5] }})['A']

    tartemp = tuple(map(int, re.search(char.replace('',' (.+) 0\n')[8:], boxcontext)[1].split(' ')))
    
    cv2.rectangle(img, (tartemp[0], h-tartemp[1]), (tartemp[2], h-tartemp[3]), (0, 0, 255), 1)
    cv2.imwrite('done.'+f, img)

    tar = h-tartemp[1]
    print(tar)


def get_targets(f) :
    if ( f[:7]=='real.l.' and f[-4:]=='.png' ):

        img = cv2.imread(f, 0)
        h = img.shape[0]
        repl = '!"#$%&\'()*+,-/:;<=>?@[\\]^_`{|}~“”、，。 《》°「‖'
        # 标点符号的代替为.

        os.system("tesseract %s %s --dpi 300 -l chi_sim makebox >nul 2>&1" %(f, f))
        boxcontext = open(f+'.box', mode='r', encoding='UTF8').read()

        context = ''.join(re.split(r' .+\n', boxcontext)).translate(str.maketrans('','', repl))

        # if MongoClient()['db']['5-19'].find({'Q':{'$regex': '^%s' %context[:5] }}).count() == 1:

        char = MongoClient()['db']['5-19'].find_one({'Q':{'$regex': '^%s' %context[:5] }})['A']

        tartemp = tuple(map(int, re.search(char.replace('',' (.+) 0\n')[8:], boxcontext)[1].split(' ')))
        
        cv2.rectangle(img, (tartemp[0], h-tartemp[1]), (tartemp[2], h-tartemp[3]), (0, 0, 255), 1)
        cv2.imwrite('done.'+f, img)
        
        os.remove(f+'.box')

        # tar = h-tartemp[1]
        # print(tar)


def main(args):

    signal.signal(signal.SIGINT, signal_handler)
    option = args[0]

    if option != '-l' and option != '-a':
        # branch.file
        if os.path.exists(option):
            get_target(option)
        else: print(' !! %s not found.'%option)

    elif option == '-l' :
        # branch.listdir
        Pool().map(get_targets, os.listdir())
        # 'real.l.*.png' -> 'real.l.done.*.png'

    elif option == '-a' :
        # branch.adb

        os.system("adb exec-out screencap -p > real.temp.0.png") ; open('real.temp.png', 'wb').write(open('real.temp.0.png', 'rb').read().replace(b'\r\n',b'\n')) # over Android 6
        # os.system("adb shell screencap -p /sdcard/screenshot.png && adb pull /sdcard/screenshot.png real.temp.png") # under Android 6

        # Image.open('real.temp.png').crop((50,250,670,1200)).save('real.png' ,'PNG') # Sumsang
        # Image.open('real.temp.png').crop((0,150,720,1440)).save('real.png' ,'PNG') # Redmi 6a
        # Image.open('real.temp.png').crop((50,300,670,1200)).save('real.png' ,'PNG') # Redmi 4x

        get_target('real.png')
        

if __name__ == "__main__":
    if sys.argv[1:] == []:
        print(" ? < <this.py> -a(db) / -l(istdir) / <filename.png>")
        print(" listdir> 'real.l.*.png' -> 'real.l.done.*.png' ")
        sys.exit(0)
    main(sys.argv[1:])
